import React, { useContext, useEffect } from "react";
import { connect } from "react-redux";

import Context from "../../Context";
import store from "../../store/store";
import api from "../../api/apiFuncs";
import { exec } from "../../api/apiFuncs";
import { msgTypes } from "../../api/api";

var WebSocketClient = require("websocket").w3cwebsocket;
var wsclient;

function Websocket(props) {
  const { setWSConnectStatus } = useContext(Context);
  useEffect(() => {
    connectWS(getServerAddress(), setWSConnectStatus);
    // return () => wsclient.close();
  }, [setWSConnectStatus]);
  return <div></div>;

  function getServerAddress() {
    try {
      return props.server.serverAddress;
    } catch (err) {
      return "127.0.0.1:8000";
    }
  }
}

function connectWS(addr, setWSConnectStatus) {
  wsclient = new WebSocketClient("wss://" + addr + "/msg");

  //send list of listening chats
  wsclient.onopen = function () {
    setWSConnectStatus(true);
    console.log("WS Connect");
    const storage = store.getState();
    Object.keys(storage.chats).map((chat, id) => {
      return api[msgTypes.subscribeToChat](chat);
    });

    // Object.keys(props.chats)
    //   .filter((key) => props.chats[key].hash)
    //   .map((key, index) => {
    //     const message = new SubscribeToChat(key);
    //     WSSend(JSON.stringify(message));
    //   });

    // function sendNumber() {
    //   if (wsclient.readyState === wsclient.OPEN) {
    //     var number = Math.round(Math.random() * 0xffffff);
    //     wsclient.send(number.toString());
    //     setTimeout(sendNumber, 1000);
    //   }
    // }
    // sendNumber();
  };

  //trying reconnect after disconnect with 2 sec delay
  wsclient.onclose = function () {
    setWSConnectStatus(false);
    console.log("WS Disconnect");
    setTimeout(() => {
      connect(setWSConnectStatus);
    }, 2000);
  };

  wsclient.onerror = function (err) {
    console.log("Connection Error: ", err);
  };

  wsclient.onmessage = function (e) {
    exec(e.data);
  };
}

function WSSend(data) {
  wsclient.send(data);
}

const mapStateToProps = (state) => {
  return {
    server: state.account.server,
  };
};

const mapDispathToProps = {};

export { WSSend };
export default connect(mapStateToProps, mapDispathToProps)(Websocket);
// export default Websocket;
